<template>
  <a-modal :width="1200" v-model:visible="showEditDialog" title="批量创建交货单" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="header">
      <p class="title">基础信息</p>
    </div>
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="6">
          <a-form-item field="gmtDelivery" label="交货日期：" label-col-flex="100px">
            <a-date-picker v-model="formInfo.gmtDelivery" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="物流方式：" label-col-flex="100px">
            <a-select v-model="formInfo.logisticType" placeholder="">
              <a-option :value="1" label="线下配送" />
              <a-option :value="2" label="快递" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物流跟踪号：" label-col-flex="100px">
            <a-input v-model="formInfo.logisticName" style="width: 200px; margin-right: 10px" placeholder="物流商" />
            <a-input v-model="formInfo.logisticsTrackNumber" placeholder="物流跟踪号" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="备注：" label-col-flex="100px">
            <a-textarea v-model="formInfo.remark" placeholder="" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="附件：" label-col-flex="100px">
            <div class="flex-wrap">
              <a-tag style="margin-right: 10px; margin-bottom: 10px" v-if="formInfo.attachment" color="arcoblue" @close="formInfo.attachment = ''" closable>
                <TextLimit :rows="1">{{ formInfo.attachment }}</TextLimit>
              </a-tag>
              <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="header flex-c">
      <p class="title">交货明细</p>
    </div>
    <a-table
      class="table-two-line"
      ref="tableRef"
      row-key="id"
      :data="purchaseOrders"
      :span-method="spanMethodAll"
      :scroll="{
        y: 'calc(84vh - 380px)',
      }"
      :columns="tableColumns"
      :expandable="expandable"
      :loading="tableLoading"
      :default-expand-all-rows="true"
      size="mini"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template v-if="item.dataIndex == 'num'" #title>
            <div class="flex-c">
              <p><span class="warningColor">*</span> <span>本次交货</span></p>
              <a-button style="margin-left: 3px; padding: 0" type="text" size="mini" @click="batchUpdateNum">全部交货</a-button>
            </div>
          </template>
          <template v-if="item.dataIndex == 'warehouseCode'" #cell="{ record }">
            <div class="order-w flex">
              <div class="order-detail-item" style="width: 200px">
                <p>
                  <span class="label">采购单号：</span>
                  <span class="highlight">{{ record.billNo }}</span>
                </p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p><span class="label">采购类型：</span>{{ record.purchaseType === 1 ? '普通采购' : '--' }}</p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p><span class="label">供应商：</span>{{ record.supplierName }}({{ record.supplierCode }})</p>
              </div>
              <div class="order-detail-item" style="width: 140px">
                <p><span class="label">采购员：</span>{{ record.purchaseUname }}</p>
              </div>
              <div class="order-detail-item" style="width: 150px">
                <div class="flex">
                  <span class="label" style="flex-shrink: 0">备注：</span>
                  <p style="width: 200px">
                    <TextLimit :val="record.remark" />
                  </p>
                </div>
              </div>
            </div>
          </template>
        </a-table-column>
      </template>
      <template #expand-row="{ record }">
        <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
          <template #columns>
            <a-table-column :width="10" />
            <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'warehouseCode'" #cell="option">
                <TextLimit :val="`${option.record.warehouseName}(${option.record.warehouseCode})`" />
              </template>
              <template v-else-if="item.dataIndex == 'img'" #cell="option">
                <ImgPopover :src="option.record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                  </template>
                </ImgPopover>
              </template>
              <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                <TextLimit :val="option.record.productName" :rows="2" />
              </template>
              <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                <ShowSpuDetailBySku :val="option.record.sku" :showLimit="true" :rows="1" />
                <p>{{ option.record.cateName || '--' }}</p>
              </template>
              <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                <TextLimit :val="getProductSpecs(option.record)" />
              </template>
              <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                <p>{{ option.record.rate }}%</p>
              </template>
              <template v-else-if="item.dataIndex == 'price'" #cell="option">
                <p class="price-type highlight">{{ option.record.priceType === 1 ? '含税' : '不含税' }}</p>
                <p>￥{{ option.record.price }}</p>
              </template>
              <template v-else-if="item.dataIndex == 'value'" #cell="option">
                <p class="price-type highlight">{{ option.record.priceType === 1 ? '含税' : '不含税' }}</p>
                <p>￥{{ Number(option.record.price * (option.record.num || 0)).toFixed(2) }}</p>
              </template>
              <template v-else-if="item.dataIndex == 'num'" #cell="option">
                <div class="cell flex-c" style="width: 140px">
                  <a-input-number :precision="0" :min="0" :max="option.record.stayAmt" v-model="option.record.num" style="width: 90px" placeholder="" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'num', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'handle'" #cell="option">
                <a-popconfirm v-if="record.billItems.length > 1" content="确定是否移除?" @ok="record.billItems.splice(option.rowIndex, 1)" type="error">
                  <a-button type="text">移除</a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import { createDeliveryOrder, findPurchasePage } from '@/api/purchase'
  import { parseJson } from '@/utils'

  onMounted(() => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentIds: {
      type: Array,
      default: () => [],
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '目的仓库',
      dataIndex: 'warehouseCode',
      width: 100,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100,
    },
    {
      title: 'SKU/类目',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: '规格名',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '采购量',
      dataIndex: 'purchaseAmt',
      width: 70,
    },
    {
      title: '已交货数',
      dataIndex: 'deliveryRealAmt',
      width: 80,
    },
    {
      title: '未交货',
      dataIndex: 'deliveryStayAmt',
      width: 70,
    },
    {
      title: '本次交货',
      dataIndex: 'num',
      width: 140,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '单价',
      dataIndex: 'price',
      width: 70,
    },
    {
      title: '本次交货金额',
      dataIndex: 'value',
      width: 85,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 60,
    },
  ]
  const rules = ref({
    gmtDelivery: [{ required: true, message: '请选择发货时间' }],
  })
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const formRef = ref()
  const tableLoading = ref(false)

  // 添加初始化数据
  async function setDefaultData() {
    formInfo.value = {
      logisticType: 1,
    }
    tableLoading.value = true
    const res: any = await findPurchasePage({
      ids: props.currentIds.join(','),
      pageNum: 1,
      pageSize: 100,
    })
    tableLoading.value = false
    purchaseOrders.value = res?.data?.records || []
    expandable.value.expandedRowKeys = purchaseOrders.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'warehouseCode') {
      return { rowspan: 1, colspan: 11 }
    }
  }
  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment = res.data.publicUrl
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number, parentId: string) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.id === parentId)
    const newVal = item[key]
    purchaseOrders.value.forEach((el: any, index: number) => {
      if (index === parentIndex) {
        el.billItems.forEach((child: any, j: number) => {
          if (j > rowIndex) child[key] = newVal
        })
      } else if (index > parentIndex) {
        el.billItems.forEach((child: any) => {
          child[key] = newVal
        })
      }
    })
  }
  // 全部交货
  function batchUpdateNum() {
    purchaseOrders.value.forEach((el: any) => {
      el.billItems.forEach((child: any) => {
        child.num = child.deliveryStayAmt
      })
    })
  }
  // 是否显示批量编辑按钮
  function showBatchIcon(parentId: string, childIndex: number) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.id === parentId)
    let parentLen = purchaseOrders.value.length
    return !(parentIndex === parentLen - 1 && childIndex === purchaseOrders.value[parentIndex].billItems.length - 1)
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 保存
  async function submitData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    if (!purchaseOrders.value.length) {
      Message.error('请最少包含一个采购明细')
      return false
    }
    let flag = false
    let list: Array<any> = []
    purchaseOrders.value.forEach((el: any) => {
      el.billItems.forEach((child: any) => {
        let obj = {
          billId: child.billId,
          deliveryAmt: child.num,
          id: child.id,
          warehouseCode: child.warehouseCode,
          warehouseName: child.warehouseName,
          remark: child.remark,
          supplierName: child.supplierName,
          supplierCode: child.supplierCode,
          supplierId: child.supplierId,
        }
        list.push(obj)
        if (!(child.num || child.num === 0)) {
          flag = true
        }
      })
    })
    if (flag) {
      Message.error('本次交货数必填')
      return false
    }
    let res: any = await createDeliveryOrder({
      ...formInfo.value,
      deliveryItems: list,
    })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
</script>
<style lang="less" scoped>
  .header {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
    border-left: 3px solid rgba(var(--primary-6), 0.5);
    padding-left: 10px;
    .title {
      margin-right: 30px;
      width: 90px;
    }
  }
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
